package com.kun.companion.core.ui.tree;

import javafx.css.PseudoClass;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * 增强型树单元格渲染器
 *
 * @param <T> 单元格数据类型
 * @author gzc
 * @since 2025/2/9
 **/
public class BaseTreeCell<T> extends TreeCell<T> {
    // 图形元素
    protected final HBox container = new HBox(5);
    protected final StackPane iconBox = new StackPane();
    protected final Label textLabel = new Label();

    public BaseTreeCell() {
        initCellComponents();
        initEventHandlers();
    }

    /**
     * 初始化单元格UI组件
     */
    protected void initCellComponents() {
        // 容器布局配置
        container.setAlignment(Pos.CENTER_LEFT);
        container.getChildren().addAll(iconBox, textLabel);

        // 图标容器样式
        iconBox.setPrefSize(16, 16);
        iconBox.getStyleClass().add("tree-icon");

        // 文本标签样式
        textLabel.getStyleClass().add("tree-text");
        textLabel.setMaxWidth(Double.MAX_VALUE);
    }

    /**
     * 初始化事件处理器
     */
    protected void initEventHandlers() {
        // 双击切换展开状态
        setOnMouseClicked(event -> {
            if (event.getClickCount() == 2 && !isEmpty()) {
                TreeItem<T> item = getTreeItem();
                if (item != null && !item.isLeaf()) {
                    item.setExpanded(!item.isExpanded());
                }
            }
        });
    }

    /**
     * 更新单元格内容
     */
    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        if (empty || item == null) {
            setGraphic(null);
            setText(null);
        } else {
            configureCellContent(item);
            applyStyleRules();
            setGraphic(container);
        }
    }

    /**
     * 配置单元格内容
     */
    protected void configureCellContent(T item) {
        if (getTreeItem() instanceof BaseTreeItem<?> baseTreeItem) {
            // 绑定图标显示
            iconBox.getChildren().setAll(
                    Optional.ofNullable(baseTreeItem.getNodeIcon().get())
                            .orElseGet(createDefaultIcon)
            );
        }
        textLabel.setText(item.toString());
    }

    /**
     * 创建默认图标
     */
    private final Supplier<Node> createDefaultIcon = () -> {
        Region icon = new Region();
        icon.getStyleClass().add("default-icon");
        return icon;
    };

    /**
     * 应用样式规则
     */
    private void applyStyleRules() {
        pseudoClassStateChanged(PseudoClass.getPseudoClass("expanded"),
                getTreeItem() != null && getTreeItem().isExpanded());
        pseudoClassStateChanged(PseudoClass.getPseudoClass("leaf"),
                getTreeItem() != null && getTreeItem().isLeaf());
    }
}